<template>
  <div class="user-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-card">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="姓名">
          <el-input 
            v-model="formInline.userName" 
            placeholder="请输入姓名" 
            clearable 
            @clear="handleClear" 
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button type="danger" @click="onBatchDelete" :disabled="!selectedUsers.length">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="users"
        border
        @selection-change="handleSelectionChange"
        :height="400"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="userId" label="用户ID" align="center" width="200">
          <template #default="scope">
            <el-tooltip
              :content="scope.row.userId"
              placement="top"
              effect="light"
            >
              <span>{{ scope.row.userId }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="name" label="姓名" align="center">
          <template #default="scope">
            {{ scope.row.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="角色" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.roleId === '1' ? 'danger' : 'info'" effect="dark">
              {{ scope.row.roleId === '1' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
          <template #default="scope">
            {{ scope.row.email || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.userId)"
              :disabled="scope.row.userId === currentUserInfo?.data?.userId"
            >删除</el-button>
            <el-button size="small" type="warning" @click="handleResetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="10"
          layout="total, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserManagementStore } from '@/store/userManagement/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'


const router = useRouter()
const route = useRoute()
const userStore = useUserManagementStore()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const formInline = reactive({
  userName: ''
})

// 从 store 获取状态
const { users, loading, error } = storeToRefs(userStore)

// 添加当前用户信息的响应式引用
const currentUserInfo = ref(JSON.parse(localStorage.getItem('userInfo')));

// 页面加载时获取数据
onMounted(async () => {
  // 检查登录状态
  const token = localStorage.getItem('jwtToken');
  const userRole = localStorage.getItem('userRole');
  
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }

  // 检查用户权限
  if (userRole?.toLowerCase() !== 'admin') {
    ElMessage.error('无权访问此页面');
    router.push('/userIndex');
    return;
  }

  try {
    const result = await userStore.fetchUsers();
    
    if (result && result.list) {
      total.value = result.list.length;
      users.value = result.list.slice(0, 10);
    } else {
      console.error('返回的数据格式不正确:', result);
      ElMessage.error('数据格式错误');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败');
  }
});

// 搜索处理
const onSearch = async () => {
  if (!formInline.userName) {
    ElMessage.warning('请输入用户名');
    return;
  }

  try {
    const result = await userStore.searchUserByName({
      name: formInline.userName.trim()
    });
    
    if (result && result.list) {
      total.value = result.list.length;
      users.value = result.list.slice(0, 10);
      currentPage.value = 1; // 重置到第一页
      
      if (result.list.length === 0) {
        ElMessage.info('未找到该用户');
      }
    } else {
      ElMessage.warning('搜索结果格式不正确');
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  }
};

// 当点击搜索框的清除按钮时，重新加载所有用户列表
const handleClear = async () => {
  try {
    const result = await userStore.fetchUsers();
    if (result && result.list) {
      total.value = result.list.length;
      currentPage.value = 1;
      users.value = result.list.slice(0, 10);
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 删除用户
const handleDelete = async (userId) => {
  // 检查是否删除自己
  const currentUserInfo = JSON.parse(localStorage.getItem('userInfo'));
  if (currentUserInfo?.data?.userId === userId) {
    ElMessage.error('不能删除当前登录用户');
    return;
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const success = await userStore.deleteUser(userId);
    if (success) {
      await handleCurrentChange(currentPage.value);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 页码改变
const handleCurrentChange = async (val) => {
  try {
    currentPage.value = val;
    const result = await userStore.fetchUsers();
    if (result && result.list) {
      total.value = result.list.length;
      const start = (currentPage.value - 1) * 10;
      const end = start + 10;
      users.value = result.list.slice(start, end);
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 选中的用户
const selectedUsers = ref([])

// 表格多选
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 批量删除
const onBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 直接构造 userIds 数组
    const userIds = selectedUsers.value.map(user => user.userId);
    console.log('要删除的用户IDs数组:', userIds);
    
    const success = await userStore.batchDeleteUsers(userIds);
    
    if (success) {
      ElMessage.success('批量删除成功');
      await handleCurrentChange(currentPage.value);
      selectedUsers.value = [];
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
    }
  }
}

// 添加路由监听，当路由变化时刷新数据
watch(
  () => route.fullPath,
  async () => {
    if (route.path === '/usermanagement') {
      try {
        currentPage.value = 1; // 重置页码
        const result = await userStore.fetchUsers({
          page: currentPage.value,
          pageSize: pageSize.value
        });
        
        if (result && result.list) {
          users.value = result.list;
          total.value = result.total;
        }
      } catch (error) {
        console.error('刷新数据失败:', error);
        ElMessage.error('刷新数据失败');
      }
    }
  }
);

// 编辑用户 - 使用路由跳转
const handleEdit = (row) => {
  router.push({
    name: 'userEdit',
    params: { userId: row.userId },
    // 保持当前的布局状态
    replace: true
  })
}

// 重置密码 - 使用路由跳转
const handleResetPassword = ({userId}) => {
  router.push({name:'passwordReset',params:{userId}})
}
</script>

<style lang="less" scoped>
.user-management {
  padding: 20px;
  height: 100%;
  background-color: #f0f2f5;

  .operation-card {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
    margin-bottom: 20px;

    .el-form {
      margin-bottom: 0;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 10px;
      }

      .el-input {
        width: 220px;
      }

      .el-button {
        margin-right: 8px;
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .table-card {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);

    .el-table {
      margin-bottom: 20px;
      
      // 表格内容垂直居中
      :deep(.el-table__cell) {
        padding: 8px 0;
      }
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
      padding-top: 20px;
      border-top: 1px solid #e8e8e8;
    }
  }

  .error-alert {
    margin-top: 20px;
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .user-management {
    padding: 10px;

    .operation-card {
      .el-form {
        .el-form-item {
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>
    